package com.gmail.ceac13;

import java.util.*;

import com.gmail.ceac13.ConnectMEService.LocalBinder;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class ConnectMEActivity extends Activity implements ServiceConnection{
    /** Called when the activity is first created. */
	private boolean rastreamentoAtivado = true;
	
	public FriendDao dao;
	
	private ListView list;
	
	private PrincipalAdapter adaptador;
	
	private ImageButton ativarBotao;
	
	private ImageButton reloadBotao;
	
	private ImageButton gerenciarAmigoBotao;
	
	public static final int MENU_CONFIG = 10;
	
	public static final int MENU_ATUALIZAR = 11;
	
	public static final int MENU_SAIR = 12;
	
	public static final int MENU_REQUISICOES = 13;
	
	public static ProgressDialog dialog;
	SharedPreferences settings;
	Timer timer;
	
	Friend usuario;
	int user_id;

	private ConnectMEServiceActions actions;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
        final ServiceConnection conexao = this;
        Intent service = new Intent(this, ConnectMEService.class);
        startService(service);
        bindService(service, conexao, Context.BIND_AUTO_CREATE);
   
        setContentView(R.layout.main);
        
        final SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
        user_id = settings.getInt("user_id", -1);
        	
        TextView nomeUsuario = (TextView) findViewById(R.id.nomeusuario);
        nomeUsuario.setText(settings.getString("user_name", ""));
        
        
        list = (ListView) findViewById(R.id.lista);
        adaptador = new PrincipalAdapter(this);
        list.setAdapter(adaptador);
        
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(ConnectMEActivity.this, MapaActivity.class);
				intent.putExtra("posicao", ((Friend)adaptador.getItem(arg2)).getPosicao());
				startActivity(intent);
			}
		});
        
        this.ativarBotao = (ImageButton) findViewById(R.id.ativarButton);
        rastreamentoAtivado = settings.getBoolean("rastreamentoAtivado", true);
        if (!rastreamentoAtivado)
        	ConnectMEActivity.this.ativarBotao.setImageResource(R.drawable.logodesativado);
        this.ativarBotao.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				SharedPreferences.Editor editor = settings.edit();
				if (ConnectMEActivity.this.rastreamentoAtivado) {
					ConnectMEActivity.this.rastreamentoAtivado = false;
					ConnectMEActivity.this.ativarBotao.setImageResource(R.drawable.logodesativado);
					actions.setAtivo(false);
					editor.putBoolean("rastreamentoAtivado", false);        		
	                editor.commit();
					Toast t = Toast.makeText(ConnectMEActivity.this, "Rastreamento Desativado.", Toast.LENGTH_SHORT);
					t.show();
				}
				else {
					actions.setAtivo(true);
					editor.putBoolean("rastreamentoAtivado", true);        		
	                editor.commit();
					ConnectMEActivity.this.rastreamentoAtivado = true;
					ConnectMEActivity.this.ativarBotao.setImageResource(R.drawable.logoativo);
					Toast t = Toast.makeText(ConnectMEActivity.this, "Rastreamento Ativado.", Toast.LENGTH_SHORT);
					t.show();
				}
			}
		});
        
        this.reloadBotao = (ImageButton) findViewById(R.id.reloadButton);
        this.reloadBotao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				atualizarLista();
			}
		});
        
        this.gerenciarAmigoBotao = (ImageButton) findViewById(R.id.gerenciarAmigos);
        this.gerenciarAmigoBotao.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				exibirAlertDialogSolicitar();
			}
		});
    }
    
    private void exibirAlertDialogSolicitar() {
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);

    	alert.setTitle("Solicitar Amizade");
    	alert.setMessage("Entre com o email do amigo que quer adicionar");

    	// Set an EditText view to get user input 
    	final EditText input = new EditText(this);
    	alert.setView(input);

    	alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int whichButton) {
	    	  String value = input.getText().toString();
	    	  dialog = ProgressDialog.show(ConnectMEActivity.this, "Atualizando", "Atualizando a sua lista de amigos. Por favor aguarde.");
	    	  //SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
	    	  String endServer = settings.getString("servidor", "http://connectme.scienceontheweb.net/");
	    	  //String endServer = settings.getString("servidor", "http://10.0.2.2/connectme/");
	    	  boolean result = false;
	    	  
	    	  try {
	    		  result = Servidor.solicitarAmizade(user_id, value, endServer);
	    	  }
	    	  finally {
	    		  dialog.dismiss();
	    	  }
	    	  if (result) {
	    		  Toast t = Toast.makeText(ConnectMEActivity.this, "Solicitação enviada com sucesso.", Toast.LENGTH_SHORT);
					t.show();
	    	  }
	    	  else {
	    		  Toast t = Toast.makeText(ConnectMEActivity.this, "Email não encontrado.", Toast.LENGTH_SHORT);
					t.show();
	    	  }
	    	}
    	});

    	alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	  public void onClick(DialogInterface dialog, int whichButton) {
    	    // Canceled.
    	  }
    	});

    	alert.show();
    }
    
    public void onStart() {
    	super.onStart();
    	//SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
        
        int user_id = settings.getInt("user_id", -1);
    	 if (user_id == -1) {
         	Intent intent = new Intent(ConnectMEActivity.this, LoginActivity.class);
 			startActivity(intent);
         }
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	//Configurações
    	//Atualizar

    	menu.add(Menu.NONE, MENU_ATUALIZAR, Menu.NONE, "Atualizar");
    	menu.add(Menu.NONE, MENU_CONFIG, Menu.NONE, "Configuracoes");
    	menu.add(Menu.NONE, MENU_SAIR, Menu.NONE, "Sair");
    	menu.add(Menu.NONE, MENU_REQUISICOES, Menu.NONE, "Requisições");
    	
    	return(super.onCreateOptionsMenu(menu));
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch (item.getItemId()) {
    	case MENU_ATUALIZAR:
			atualizarLista();
    	return true;
    	case MENU_CONFIG:
    		Intent intentConf = new Intent(this, ConfiguracoesActivity.class);
			startActivity(intentConf);
    	return true;
    	case MENU_SAIR:
    		//SharedPreferences settings = getSharedPreferences("ConnectMe",MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("user_id", -1);
			editor.commit();
    		Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
        return true;
    	case MENU_REQUISICOES:
    		ConnectMEActivity.dialog = ProgressDialog.show(this, "Atualizando", "Atualizando a sua lista de requisições. Por favor aguarde.");
    		Intent intent1 = new Intent(ConnectMEActivity.this, RequisicoesActivity.class);
    		startActivity(intent1);			
    	return true;
    	default:
    	return super.onOptionsItemSelected(item);
    	}
   	}

    public void exibirAlerta() {
			dialog = ProgressDialog.show(ConnectMEActivity.this, "Atualizando", "Atualizando a sua lista de amigos. Por favor aguarde.");
			
			timer = new Timer();
	        timer.schedule(new RemindTask(), 2000);					    
    }
    class RemindTask extends TimerTask {
        public void run() {
        	dialog.dismiss();
            timer.cancel(); //Terminate the timer thread
        }
    }
	@Override
	public void onServiceConnected(ComponentName arg0, IBinder arg1) {
		LocalBinder binder = (LocalBinder) arg1;
		actions = binder.getActions();
		actions.setAdapter(this.adaptador);
	}

	@Override
	public void onServiceDisconnected(ComponentName arg0) {
	}
	
	private void atualizarLista() {
		dialog = ProgressDialog.show(ConnectMEActivity.this, "Atualizando", "Atualizando a sua lista de amigos. Por favor aguarde.");
		atualiza();
	}
	
	private void atualiza() {
		new Thread() {
			@Override
			public void run() {
				try {
					actions.atualiza();
				} catch(Exception e) {
					e.printStackTrace();
				}
				fecharDialog();
			}
		}.start();
	}
	private void fecharDialog() {
		try {
			dialog.dismiss();
		}catch(Exception e) {
			Log.i("ConnectME", e.toString());
		}
	}
}